package com.zhaojun.cloud.service.redis.provider;

import com.zhaojun.cloud.service.api.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * wwj
 * 2018/12/5  11:15
 * <p>
 * <p>
 * 时间默认秒单位
 */
@RestController
public class RedisServiceProvider implements RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * String
     */
    @Override
    public String get(@PathVariable String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public Boolean set(@RequestParam String key, @RequestParam String value) {
        redisTemplate.opsForValue().set(key, value);
        return true;
    }

    /**
     * Hash
     */
    @Override
    public String hget(@RequestParam String hkey, @RequestParam String key) {
        return (String) redisTemplate.boundHashOps(hkey).get(key);
    }

    @Override
    public Boolean hset(@RequestParam String hkey, @RequestParam String key, @RequestParam String value) {
        redisTemplate.boundHashOps(hkey).put(key, value);
        return true;
    }

    @Override
    public int hsize(@RequestParam String hkey) {
        return redisTemplate.boundHashOps(hkey).size().intValue();
    }

    @Override
    public Set hkeys(@RequestParam String hkey) {
        return redisTemplate.boundHashOps(hkey).keys();
    }

    @Override
    public Collection hvalues(@RequestParam String hkey) {
        return redisTemplate.boundHashOps(hkey).values();
    }

    /**
     * 自增长 增减
     */
    @Override
    public Long incr(@PathVariable String key) {
        return redisTemplate.boundValueOps(key).increment(1);
    }

    @Override
    public Long decr(@PathVariable String key) {
        return redisTemplate.boundValueOps(key).increment(-1);
    }

    @Override
    public Boolean expire(@RequestParam String key, @RequestParam Long second) {
        return redisTemplate.expire(key, second, TimeUnit.SECONDS);
    }

    @Override
    public Long ttl(@PathVariable String key) {
        return redisTemplate.getExpire(key);
    }

    @Override
    public Boolean del(@PathVariable String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public Long hdel(@RequestParam String hkey, @RequestParam String key) {
        return redisTemplate.boundHashOps(hkey).delete(key);
    }
}
